<template>
  <div style="position: relative; height: 100%">
    <div class="work-flow-list">
      <div :id="searchConditionContainerId"></div>
      <div class="workflow-list-header">
        <div class="pending-list-top">
          <span v-if="columnsName">{{ decodeURIComponent(columnsName) }}</span>
          <span>({{ pagination.total }})</span>
        </div>
        <div class="pending-list-header">
          <div class="search-part">
            <div style="display: inline-block; width: 272px">
              <a-input-search placeholder="请输入模板名称关键字"
                              style="width: 272px"
                              :allowClear="true"
                              @change="onInputSearchValueChange"
                              @search="doSearch" />
            </div>
            <div style="margin-left: 12px; display: flex">
              <SearchCondition :containerParentId="searchConditionContainerId"
                               :conditions="searchConditions"
                               @valueChange="doSeniorSearch"
                               @expandChange="expandChange"></SearchCondition>
            </div>
          </div>
        </div>
      </div>

      <div class="pending-list-content">
        <AVirtuallyTable rowKey="id"
                         ref="avirtuallyTable"
                         :pagination="true"
                         :paginationOption="pagination"
                         :pageSizeOptions="pagination.pageSizeOptions"
                         size="small"
                         :columns="columns"
                         :openVirtuallyModel="true"
                         :dataSource="dataSource"
                         @paginationChange="switchPage"
                         @paginationShowSizeChange="paginationShowSizeChange">
          <span slot="manual"
                slot-scope="{ text, record }"
                @click="openProcessInstruction(record)">
            <i class="ico16 flowInstructions_16"></i>
            {{ text }}
          </span>
          <span slot="templateName"
                slot-scope="{ text, record }"
                class="lick-color"
                @click="newCol(record)">
            {{ text }}
          </span>
          <span slot="belongMember"
                slot-scope="{ text, record }"
                class="lick-color"
                @click="openUserCard(record)">
            {{ text }}
          </span>
        </AVirtuallyTable>
      </div>
    </div>
  </div>
</template>

<script>
  import { getParams, loadComponentsThemeDefaultCSS } from '../../utils';
  import SearchCondition from '@/components/search-condition/index.vue';
  import AVirtuallyTable from '@/ant-virtually-table/table.vue';
  import { formatRequestDataToJSON } from '@/utils/api';

  const subAppMap = {
    // 表单公文-发文
    401: 1,
    // 表单公文-收文
    402: 2,
    // 表单公文-签报
    404: 3
  };
  export default {
    name: 'WorkflowList',
    components: {
      SearchCondition,
      AVirtuallyTable
    },
    data() {
      return {
        searchConditionContainerId: 'search-condition-container-parent',
        dataSource: [],
        columns: [],
        columnsName: null,
        pagination: {
          page: 1,
          // pageSize: 20,
          total: 0
          // pageSizeOptions: ['10', '20', '30', '40', '50'],
          // showTotal: (total) => `共${total}条记录`,
          // showSizeChanger: true
        },
        searchValue: '',
        searchConditions: [],
        globalParam: {},
        seniorConditions: null
      };
    },
    async created() {
      await this.initTableHeader();
      this.initTableData();
      loadComponentsThemeDefaultCSS(window._ctxPath + window._ctpSkinUrl);
    },
    methods: {
      async initTableHeader() {
        const {
          fragmentId = '',
          ordinal = '',
          bigTitleIndex = '',
          name
        } = getParams(window.location.search);
        this.columnsName = name;
        const headerParams = {
          // 页面唯一标识（取值参照PageKey）
          key: 'LIST_PROCESS_CENTER_SECTION',
          // 终端 0 pc 1 mobile （取值参照PlatformType）
          platform: 0,
          arguments: {
            fragmentId,
            ordinal,
            bigTitleIndex,
            userId: window._currentUser.id
          }
        };
        const url = `${window._ctxPath}/rest/global/metadata/list`;
        await window.axios.post(url, headerParams).then((ret) => {
          if (ret.data.data) {
            let { tableColumns, searchConditions, globalParam } = ret.data.data;
            this.globalParam = globalParam;
            this.searchConditions = searchConditions.filter((item) => item.key !== 'c_templateName');

            // 流程使用说明书、模板名称、所属人，特殊渲染
            const customFields = ['manual', 'templateName', 'belongMember'];
            tableColumns.forEach((item) => {
              delete item.extra;
              item.dataIndex = item.key;
              if (customFields.includes(item.key)) {
                item.scopedSlots = { customRender: item.key };
              }
              item.dropdownMenus = {
                fieldset: true
              };
            });
            this.columns = tableColumns;
          }
        });
      },
      initTableData() {
        let sendSearch;
        if (this.seniorConditions) {
          sendSearch = this.seniorConditions;
        } else {
          this.seniorConditions = sendSearch = {
            fragmentId: this.globalParam.fragmentId,
            ordinal: this.globalParam.ordinal,
            column: this.globalParam.columns
          };
        }

        const sendParams = [
          { page: this.pagination.page, size: this.pagination.pageSize },
          sendSearch
        ];
        const args = `managerMethod=showSection&arguments=${formatRequestDataToJSON(sendParams)}`;
        const url = `${
          window._ctxPath
        }/ajax.do?method=ajaxAction&managerName=processAssetsManager&rnd=${Math.random()}`;

        if (this.cancelToken && this.cancelToken.cancel) {
          this.cancelToken.cancel();
          this.cancelToken = null;
        }
        this.cancelToken = axios.CancelToken.source();

        window.axios.post(url, args, { cancelToken: this.cancelToken.token }).then((data) => {
          const result = data.data;
          if (result) {
            this.pagination.total = result.total;
            let _data = [];
            result.data.forEach((item) => {
              let ext = {};
              let obj = { ext: ext };
              _data.push(obj);
              item.forEach((i) => {
                obj[i.key] = i['display'];
                ext[i.key] = i;
              });
            });
            this.dataSource = _data;
          }
        });
      },
      /**
       * 根据模板名称值改变
       * @param e
       */
      onInputSearchValueChange(e) {
        this.searchValue = e.target.value;
        this.seniorConditions.c_templateName = this.searchValue;
      },
      /**
       * 根据模板名称搜索
       * @param val
       */
      doSearch(val) {
        this.searchValue = val;
        this.seniorConditions.c_templateName = this.searchValue;
        this.pagination = { ...this.pagination, page: 1 };
        this.initTableData();
      },
      /**
       * 切换页码
       * @param page
       * @param pageSize
       */
      switchPage(page, pageSize) {
        this.pagination.page = page;
        this.pagination.pageSize = pageSize;
        this.initTableData();
      },
      paginationShowSizeChange(current, size) {
        this.pagination.page = 1;
        this.pagination.pageSize = size;
        this.initTableData();
      },
      /**
       * 高级搜索
       * @param data
       */
      doSeniorSearch(data) {
        this.pagination.page = 1;
        this.seniorConditions = {
          fragmentId: this.globalParam.fragmentId,
          ordinal: this.globalParam.ordinal,
          column: this.globalParam.columns,
          c_templateName: this.searchValue || '',
          beginPublishTime: data.publishTime?.startDate || '',
          endPublishTime: data.publishTime?.endDate || '',
          ...data
        };
        delete this.seniorConditions.publishTime;
        this.initTableData();
      },
      /**
       * 打开流程使用说明书窗口
       * @param record
       */
      openProcessInstruction(record) {
        let templateId = record.ext.manual.templateId;
        let url = `${window._ctxPath}/templateInsController.do?method=templateIns&id=${templateId}&showAll=1`;
        window.$.dialog({
          url: url,
          width: window.screen.availWidth,
          height: window.screen.availHeight - 120,
          title: $.i18n('template.ins.title.js')
        });
      },
      /**
       * 人员卡片
       * @param record
       */
      openUserCard(record) {
        let memberId = record.ext.belongMember.memberId;
        $.PeopleCard({
          targetWindow: window.getCtpTop(),
          memberId: memberId
        });
      },
      /**
       * 新建事项
       * @param record
       * @returns {Promise<void>}
       */
      async newCol(record) {
        let templateId = record.ext.manual.templateId;
        let moduleType = record.ext.templateName.moduleType;
        const args = `managerMethod=checkAuth&arguments=${JSON.stringify([
          templateId,
          String(moduleType)
        ])}`;
        const url = `${
          window._ctxPath
        }/ajax.do?method=ajaxAction&managerName=processAssetsManager&rnd=${Math.random()}`;
        let data = await window.axios.post(url, args).then((ret) => ret.data);
        if (data !== '') {
          $.alert(data);
          return;
        }
        if (moduleType === 1) {
          // 协同
          let url = `${window._ctxPath}/collaboration/collaboration.do?method=newColl&templateId=${templateId}&from=templateNewColl`;
          window.openCtpWindow({
            url: url
          });
          return;
        }
        this.openEdocWin(moduleType, templateId);
      },
      /**
       * 新建公文
       * @param moduleType
       * @param templateId
       * @returns {Promise<void>}
       */
      async openEdocWin(moduleType, templateId) {
        const url = `${
          window._ctxPath
        }/ajax.do?method=ajaxAction&managerName=edocManager&rnd=${Math.random()}`;
        const args = `managerMethod=checkCreateRoleAuth&arguments=${JSON.stringify([
          String(moduleType)
        ])}`;
        let data = await window.axios.post(url, args).then((ret) => ret.data);
        if (data != '') {
          $.alert(data);
          return;
        }
        const subApp = subAppMap[moduleType];
        window.openCtpWindow({
          url: `${window._ctxPath}/govdoc/govdoc.do?method=newGovdoc&from=template&sub_app=${subApp}&templateId=${templateId}`
        });
      },
      expandChange() {
        this.$nextTick(() => {
          this.$refs.avirtuallyTable && this.$refs.avirtuallyTable.resizeTable();
        });
      }
    }
  };
</script>

<style>
  @import url('../../assets/css/common.css');
</style>
<style scoped lang="scss">
  .work-flow-list {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    display: flex;
    padding-left: 16px;
    flex-direction: column;
    background-color: #ffffff;
    .workflow-list-header {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      padding: 12px 16px 12px 0;
    }
    .pending-list-top {
      // line-height: 57px;
      font-size: 16px;
      font-weight: 600;
      color: #333333;
    }

    .pending-list-header {
      display: flex;
      // padding: 10px 10px 15px 20px;
      box-sizing: border-box;
      justify-content: flex-end;
    }

    .search-part {
      // flex: 1;
      display: flex;
      justify-content: flex-end;
      overflow: hidden;
      margin-left: 100px;
    }

    .pending-list-content {
      flex: 1;
      padding: 0;
      position: relative;
      overflow: hidden;
      > div {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
      }
    }

    .lick-color {
      cursor: pointer;
      color: var(--theme-brand6, #296fbe);
    }
  }
</style>
